<template>
  <div id="picture">
    <MainHead name="图片" :flag="flag" :terms="terms" :example="example" @query="query(1)">
      <template slot="header">
        <el-upload ref="upload" class="upload-btn" :action="uploadUrl" :on-error="onError" :on-success="onSuccess"
          :multiple="false" :show-file-list="false">
          <el-button :size="$store.state.size" type="success" icon="el-icon-upload">
            上传图片
          </el-button>
        </el-upload>
      </template>
    </MainHead>
    <el-row class="image-list" :style="{ height: $store.state.sizes.pTableHei + 'px' }">
      <el-col v-for="(item, index) in result.rows" :xs="8" :sm="7" :md="6" :xl="4">
        <el-result icon="success" :title="item.remark ? item.remark : (index + 1).toString()"
          :subTitle="item.time + '   ' + item.space">
          <template slot="icon">
            <el-image @contextmenu="modify(item)" class="image" :src="$store.state.conf.host + '/' + item.path"
              :preview-src-list="srcList">
            </el-image>
          </template>
          <template slot="extra">
            <el-button type="primary" size="mini" @click="copy(item)">复制</el-button>
            <el-button type="info" size="mini" @click="remark(item)">备注</el-button>
            <el-button type="danger" size="mini" @click="delate(item)">删除</el-button>
          </template>
        </el-result>
      </el-col>
    </el-row>
    <el-pagination :current-page="example.page" :page-sizes="[10, 20, 50, 100]" :page-size="example.size"
      layout="total, sizes, prev, pager, next, jumper" :total="result.total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />

    <el-dialog :title="row.path" :visible.sync="flag.modify" :close-on-click-modal="false" width="30%">
      <el-button :plain="true" type="info" style="width:100%" @click="copy(row, true)">复制为MarkDown语法
      </el-button>
      <br><br>
      <el-button :plain="true" type="success" style="width:100%">
        <el-upload class="update-btn" ref="update" :data="row" :action="updateImgUrl" :on-error="onError"
          :on-success="onSuccess" :multiple="false" :show-file-list="false">
          更新图片内容(ctrl+v)
        </el-upload>
      </el-button>
    </el-dialog>

  </div>
</template>

<script>
  import {
    Vue,
    Component,
    Prop
  } from "vue-property-decorator";
  import Template from '@/components/template/manage.vue';
  import MainHead from '@/components/template/mainHeader.vue';

  @Component({
    components: {
      Template,
      MainHead
    }
  })
  export default class Picture extends Vue {
    url = 'picture';
    imgUrl = 'picture/img';
    uploadUrl = (process.env.VUE_APP_BASE_URL ? "/api/" : "/") + this.url;
    updateImgUrl = (process.env.VUE_APP_BASE_URL ? "/api/" : "/") + this.imgUrl;
    flag = {
      list: true,
      save: false,
      update: false,
      del: true,
      title: true,
      modify: false
    }
    terms = [{
      code: 'remark',
      desc: '备注'
    }, {
      code: 'startTime',
      datePicker: true,
      valueFormat: 'yyyy-MM-dd HH:mm:ss',
      type: 'datetime',
      desc: '开始时间'
    }, {
      code: 'endTime',
      datePicker: true,
      valueFormat: 'yyyy-MM-dd HH:mm:ss',
      type: 'datetime',
      desc: '结束时间'
    }]

    srcList = [];
    row = {};
    example = {
      page: 1,
      size: 20
    };
    result = {
      rows: [],
      total: 0
    };
    handleSizeChange(val) {
      this.example.size = val
      this.query()
    }
    handleCurrentChange(val) {
      this.example.page = val
      this.query()
    }
    query(page) {
      const that = this
      if (page != null) {
        this.example.page = page
      }
      this.$get(that.url, that.example).then(rsp => {
        that.srcList = [];
        if (rsp) {
          that.result = rsp
          rsp.rows.forEach(item => {
            that.srcList.push(that.$store.state.conf.host + '/' + item.path);
          })
        } else {
          that.result = {
            rows: [],
            total: 0
          }
        }
      })
    }

    copy(row, md) {
      const that = this;
      const host = this.$store.state.conf.host;
      let path = host + "/" + row.path;
      if (md) {
        path = "![](" + path + ")";
      }
      this.$copyText(path).then(e => {
        that.$showMessage("success", "复制成功");
        that.flag.modify = false;
      }, e => {
        that.$showMessage("success", "复制失败");
        that.flag.modify = false;
      })
    }

    remark(row) {
      const that = this
      this.$prompt('请输入备注信息', '备注', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[\S]{1,64}$/,
        inputErrorMessage: '备注不能输入空格,且长度不超过64位',
        distinguishCancelAndClose: true,
        showClose: false,
        beforeClose: (action, instance, done) => {
          if (action === 'close') {
            return
          }
          done()
        }
      }).then(({
        value
      }) => {
        console.log(value);
        const param = JSON.parse(JSON.stringify(row));
        param.remark = value;
        that.$put(that.url, param).then(rsp => {
          if (rsp) {
            that.query();
          }
        });
      }).catch(() => {})
    }

    modify(row) {
      this.flag.modify = true;
      this.row = row;
      // 去掉默认事件
      const that = this;
      document.oncontextmenu = function(e) {
        if(that.flag.modify){
          e.preventDefault();
        }
      };
    }

    delate(row) {
      const that = this
      this.$confirm('确定要删除该图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$delete(that.url, row).then(function(response) {
          if (response) {
            that.query()
          }
        })
      }).catch(() => {
        that.showMessage('info', '已取消删除')
      })
    }

    onError(err, file, fileList) {
      that.$showMessage('error', file.name + "上传失败", true)
      console.log(err);
    }
    onSuccess(response, file, fileList) {
      if (response.success == false) {
        this.$showMessage('error', response.message, true);
      } else {
        this.$showMessage('success', response.message, true)
        this.query();
        this.flag.modify = false;
      }
      this.$refs.upload.clearFiles();
    }

    getClipboardFiles(event) {
      let items = event.clipboardData && event.clipboardData.items;
      let file = null
      if (items && items.length) {
        // 检索剪切板items
        for (var i = 0; i < items.length; i++) {
          if (items[i].type.indexOf('image') !== -1) {
            file = items[i].getAsFile()
          }
        }
      }
      if (file) {
        const that = this;
        this.$confirm('是否要上传剪切板中复制的图片?', '提示', {
          confirmButtonText: '是的',
          cancelButtonText: '不用',
          type: 'warning'
        }).then(() => {
          let data = null;
          let url = this.url;
          if (that.flag.modify) {
            data = this.row;
            url = this.imgUrl;
          }
          this.$upload(file, url, data).then(rsp => {
            if (rsp) {
              that.flag.modify = false;
              that.query();
            }
          });
        }).catch(() => {})
      }
    }

    created() {
      this.query(1);
      document.addEventListener('paste', this.getClipboardFiles);
    } //生命周期 - 创建完成（可以访问当前this实例）
    mounted() {} //生命周期 - 挂载完成（可以访问DOM元素）
    beforeCreate() {} //生命周期 - 创建之前
    beforeMount() {} //生命周期 - 挂载之前
    beforeUpdate() {} //生命周期 - 更新之前
    updated() {} //生命周期 - 更新之后
    beforeDestroy() {
      document.removeEventListener('paste', this.getClipboardFiles);
    } //生命周期 - 销毁之前
    destroyed() {} //生命周期 - 销毁完成
    activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
  }
</script>
<style scoped>
  .upload-btn {
    padding-left: 10px;
  }

  .network-switch {
    padding-left: 20px;
  }

  .switch-label {
    float: left;
    font-size: 16px;
    font-weight: bold;
  }

  .image-list {
    overflow-y: auto;
  }

  .image {
    height: 120px;
    width: 200px;
  }
</style>
